package com.dlc.shop.user.platform.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.dlc.shop.bean.dto.AppConnectDTO;
import com.dlc.shop.bean.event.allinpay.CreateAllinpayMemberEvent;
import com.dlc.shop.bean.model.UserExtension;
import com.dlc.shop.common.allinpay.constant.PaySysType;
import com.dlc.shop.common.bean.PaySettlementConfig;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.security.common.model.AppConnect;
import com.dlc.shop.security.common.service.AppConnectService;
import com.dlc.shop.service.SysConfigService;
import com.dlc.shop.service.UserExtensionService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author gaozijie
 * @date 2023-11-10
 */
@Component
@AllArgsConstructor
public class AllinpayUserTask {

    private final Logger logger = LoggerFactory.getLogger(AllinpayUserTask.class);

    private final SysConfigService sysConfigService;
    private final UserExtensionService userExtensionService;
    private final AppConnectService appConnectService;

    private final ApplicationContext applicationContext;

    /**
     * 创建通联个人会员
     * （此定时任务默认关闭，若要使用需要去xxl-job后台打开）
     */
    @XxlJob("createAllinpayMember")
    public void createAllinpayMember() {
        logger.info("(定时任务)用户创建通联个人会员...");
        // 查询是否开启通联
        PaySettlementConfig config = sysConfigService.getSysConfigObject(Constant.PAY_SETTLEMENT_CONFIG, PaySettlementConfig.class);
        if (!Objects.equals(config.getPaySettlementType(), PaySysType.ALLINPAY.value())) {
            return;
        }
        CreateAllinpayMemberEvent event = new CreateAllinpayMemberEvent();
        // 查询未创建会员的用户
        List<UserExtension> userExtensions = userExtensionService.list(new LambdaQueryWrapper<UserExtension>()
                .eq(UserExtension::getAllinpayCreate, 0));
        if (CollectionUtils.isEmpty(userExtensions)) {
            return;
        }
        event.setUserIds(userExtensions.stream().map(UserExtension::getUserId).toList());
        // 查询绑定支付标识
        List<AppConnect> appConnects = appConnectService.list(new LambdaQueryWrapper<AppConnect>()
                .in(AppConnect::getUserId, event.getUserIds()));
        if (!CollectionUtils.isEmpty(appConnects)) {
            List<AppConnectDTO> appConnectDTOList = appConnects.stream().map(x -> new AppConnectDTO(x.getUserId(), x.getAppId(), x.getTempUid())).collect(Collectors.toList());
            event.setAppConnects(appConnectDTOList);
        }
        // 发送事件批量创建会员
        applicationContext.publishEvent(event);
        logger.info("(定时任务)用户创建通联个人会员 - 成功：{}，失败:{}", event.getSuccessCount(), event.getUserIds().size()-event.getSuccessCount());
    }

}
